package com.qianfeng.smartplatform.service.impl;/*
 *@Description:
 *@author:赵健
 *@Date:zjzzz 2022/9/7 16:48
 */

import com.qianfeng.smartplatform.cache.CategoryCache;
import com.qianfeng.smartplatform.constans.ResultCode;
import com.qianfeng.smartplatform.event.CategoryChangeEvent;
import com.qianfeng.smartplatform.exceptions.AddDataException;
import com.qianfeng.smartplatform.exceptions.FindDataException;
import com.qianfeng.smartplatform.mapper.CategoryMapper;
import com.qianfeng.smartplatform.pojo.SysCategory;
import com.qianfeng.smartplatform.pojo.SysUserInfo;
import com.qianfeng.smartplatform.service.CategoryService;
import com.qianfeng.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private CategoryCache categoryCache;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public void addCategory(SysCategory category) {
        //校验数据
        SysUserInfo userInfo = SecurityUtils.getLoginUser();
        category.setCreateBy(userInfo.getUsername());
        //添加之前查询数据是否存在
        SysCategory sysCategory = categoryMapper.findByCategoryName(category.getCategoryName());
        //判断查询出来的分类是不是被删除了，如果是删除了就增加新的数据，没有删除就抛异常
        //老的数据重命名，新的数据用正常名字
        if (sysCategory != null && sysCategory.getStatus() == 1) {
            throw new AddDataException("分类已存在", ResultCode.DATA_ALREADY_EXIST);
        } else if (sysCategory != null && sysCategory.getStatus() == 0) {
            sysCategory.setCategoryName(sysCategory.getCategoryName()+"teshuzifu");
            //更新数据
            sysCategory.setUpdateBy(userInfo.getUsername());
            categoryMapper.updateCategory(sysCategory);
        }
        //添加数据
        categoryMapper.addCategory(category);
        //更新缓存
        applicationContext.publishEvent(new CategoryChangeEvent());
    }

    @Override
    public List<SysCategory> findAllCategories() {
        //查询缓存
        List<SysCategory> categoryList = categoryCache.getCategoryList();
        return categoryList.stream().filter(category -> category.getStatus() == 1).collect(Collectors.toList());
    }

    @Override
    public SysCategory findById(Long cId) {
        SysCategory sysCategory = categoryCache.get(cId);
        Assert.notNull(sysCategory,()->{
            throw new FindDataException("分类不存在", ResultCode.DATA_NOT_EXIST);
        });
        return sysCategory;
    }
}
